package com.bwc.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwc.common.R;
import com.bwc.domain.User;
import com.bwc.service.UserService;
//import com.bwc.utils.SendSms;
import com.bwc.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("sendMsg")
    public R<String> sendMsg(HttpServletRequest httpServletRequest,@RequestBody User user){
        //获得号码
        String phone = user.getPhone();
        //生成验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //调用发送短信的API
//        try {
//            SendSms.send();
//        }catch (Exception ex){
//            ex.printStackTrace();
//        }

        log.info("code:{}",code);
        //要把生成的验证码保存在服务端的Session中来做校验
        httpServletRequest.getSession().setAttribute(phone,code);

        return R.success("发送验证码成功");
    }

    @PostMapping("login")
    public R<User> login(@RequestBody Map map, HttpServletRequest httpServletRequest){

        //获取前端发送过来的手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //获得之前发送给手机，保存在了服务端的验证码数据
        String codeInSession  = httpServletRequest.getSession().getAttribute(phone).toString();

        //进行比对
         if(code.equals(codeInSession)){
             LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
             lambdaQueryWrapper.eq(User::getPhone,phone);
             User user = userService.getOne(lambdaQueryWrapper);
             if(user==null) {
                 user = new User();
                 user.setPhone(phone);
                 user.setStatus(1);
                 userService.save(user);
             }
             httpServletRequest.getSession().setAttribute("user",user.getId());
             return R.success(user);

         }

        return R.error("验证码错误");
    }


}
